sap.ui.define([
	"sap/ui/core/mvc/Controller",
	"sap/ui/model/json/JSONModel",
], function (
	Controller,
	JSONModel
) {
	"use strict";

	return Controller.extend("firorworkshop185.controller.CreateOrder", {

		onInit: function () {
			var oEventBus = sap.ui.getCore().getEventBus();
			oEventBus.subscribe("createOrderEventChannel", "initInfo", this.initInfo, this);
		},

		async initInfo() {
			var oProductInput = this.getView().byId("productInput");
			oProductInput.setValue("");
			var oCustomerInput = this.getView().byId("customerInput");
			oCustomerInput.setValue("");
			var oIssueContentTextArea = this.getView().byId("issueContentTextArea");
			oIssueContentTextArea.setValue("");
			var oRepairContentTextArea = this.getView().byId("repairContentTextArea");
			oRepairContentTextArea.setValue("");

			var oModel = this.getView().getModel('info');
			const obj1 = {
				productItem: null,
				customerItem: null,
				getInfoCompleted: true
			};
			oModel.setData({
				...oModel.oData,
				createOrderDetail: obj1
			});

			let productItemPromise = this.getInfoItem("/ENTITY002Set");
			let customerItemPromise = this.getInfoItem("/ENTITY003Set");

			let [productItemList, customerItemList] = await Promise.all([productItemPromise, customerItemPromise]);

			let obj = {
				ENTITY002SetChoose: productItemList.results,
				ENTITY003SetChoose: customerItemList.results,
			}
			var oModel = new JSONModel(obj);
			this.getView().setModel(oModel);
		},

		getInfoItem(url) {
			return new Promise((resolve, reject) => {
				var oModel = new sap.ui.model.odata.v2.ODataModel("/sap/opu/odata/sap/ZGBLMTORDER_TRN_SRV/", {
					serviceUrl: "/sap",
					useBatch: false
				});

				oModel.read(url, {
					success: function (oData, oResponse) {
						resolve(oData);
					},
					error: function (oError) {
						reject(oError);
					}
				});
			});
		},

		/**
		 * productFragment相关的方法
		 */
		onValueHelpRequestProduct: function () {
			var oView = this.getView();
			var that = this;

			if (!this._productValueHelpDialog) {
				this._productValueHelpDialog = this.loadFragment({
					name: "firorworkshop185.view.fragment.CreateProductNumber",
					controller: this
				}).then(function (oValueHelpDialog) {
					oView.addDependent(oValueHelpDialog);
					return oValueHelpDialog;
				});
			}
			this._productValueHelpDialog.then(function (oValueHelpDialog) {
				this._configProductValueHelpDialog();
				oValueHelpDialog.open();

				var oSelectDialog = sap.ui.core.Fragment.byId(that.getView().getId(), "productSearchSelectDialog");
				oSelectDialog.getBinding("items").filter([new sap.ui.model.Filter("productID", sap.ui.model.FilterOperator.Contains, "")]);
			}.bind(this));
		},

		_configProductValueHelpDialog: function () {
			var sInputValue = this.byId("productInput").getValue(),
				oModel = this.getView().getModel(),
				aProducts = oModel.getProperty("/ENTITY002SetChoose");

			aProducts.forEach(function (oProduct) {
				oProduct.selected = (oProduct.productID === sInputValue);
			});
			oModel.setProperty("/ENTITY002SetChoose", aProducts);
		},

		onProductSearch: function (oEvent) {
			var sValue = oEvent.getParameter("value");
			var oFilter = new sap.ui.model.Filter("productID", sap.ui.model.FilterOperator.Contains, sValue);
			var oBinding = oEvent.getParameter("itemsBinding");
			oBinding.filter([oFilter]);
		},

		onProductValueHelpDialogClose: function (oEvent) {
			var oSelectedItem = oEvent.getParameter("selectedItem"),
				oInput = this.byId("productInput");

			if (!oSelectedItem) {
				oInput.resetProperty("value");
				this.chooseProductInfo(null);
				return;
			}

			oInput.setValue(oSelectedItem.getTitle());
			this.chooseProductInfo(oSelectedItem.getTitle());
		},

		async chooseProductInfo(productId) {
			var oModel = this.getView().getModel('info');
			const obj = {
				productItem: null,
				customerItem: oModel.oData.createOrderDetail.customerItem,
				getInfoCompleted: false
			};
			oModel.setData({
				...oModel.oData,
				createOrderDetail: obj
			});

			if (productId) {
				let productItem = await this.getInfoItem("/ENTITY002Set(productID='" + productId + "',languageKey='EN')")
				obj.productItem = productItem;
			}
			obj.getInfoCompleted = true;
			oModel.setData({
				...oModel.oData,
				createOrderDetail: obj
			});
		},

		/**
		 * productFragment相关的方法结束
		 */


		/**
		 * customerFragment相关的方法
		 */
		onValueHelpRequestCustomer: function () {
			var oView = this.getView();
			var that = this;

			if (!this._customerValueHelpDialog) {
				this._customerValueHelpDialog = this.loadFragment({
					name: "firorworkshop185.view.fragment.CreateCustomerId",
					controller: this
				}).then(function (oValueHelpDialog) {
					oView.addDependent(oValueHelpDialog);
					return oValueHelpDialog;
				});
			}
			this._customerValueHelpDialog.then(function (oValueHelpDialog) {
				this._configCustomerValueHelpDialog();
				oValueHelpDialog.open();

				var oSelectDialog = sap.ui.core.Fragment.byId(that.getView().getId(), "CustomerSearchSelectDialog");
				oSelectDialog.getBinding("items").filter([new sap.ui.model.Filter("customerNo", sap.ui.model.FilterOperator.Contains, "")]);
			}.bind(this));
		},

		_configCustomerValueHelpDialog: function () {
			var sInputValue = this.byId("customerInput").getValue(),
				oModel = this.getView().getModel(),
				aCustomers = oModel.getProperty("/ENTITY003SetChoose");

			aCustomers.forEach(function (oCustomer) {
				oCustomer.selected = (oCustomer.customerNo === sInputValue);
			});
			oModel.setProperty("/ENTITY003SetChoose", aCustomers);
		},

		onCustomerSearch: function (oEvent) {
			var sValue = oEvent.getParameter("value");
			var oFilter = new sap.ui.model.Filter("customerNo", sap.ui.model.FilterOperator.Contains, sValue);
			var oBinding = oEvent.getParameter("itemsBinding");
			oBinding.filter([oFilter]);
		},

		onCustomerValueHelpDialogClose: function (oEvent) {
			var oSelectedItem = oEvent.getParameter("selectedItem"),
				oInput = this.byId("customerInput");

			if (!oSelectedItem) {
				oInput.resetProperty("value");
				this.chooseCustomerInfo(null);
				return;
			}

			oInput.setValue(oSelectedItem.getTitle());
			this.chooseCustomerInfo(oSelectedItem.getTitle());
		},

		async chooseCustomerInfo(customerId) {
			var oModel = this.getView().getModel('info');
			const obj = {
				productItem: oModel.oData.createOrderDetail.productItem,
				customerItem: null,
				getInfoCompleted: false
			};
			oModel.setData({
				...oModel.oData,
				createOrderDetail: obj
			});

			if (customerId) {
				let customerItem = await this.getInfoItem("/ENTITY003Set(customerNo='" + customerId + "',languageKey='EN')")
				obj.customerItem = customerItem;
			}
			obj.getInfoCompleted = true;
			oModel.setData({
				...oModel.oData,
				createOrderDetail: obj
			});
		},
		/**
		 * customerFragment相关的方法结束
		 */

		cancelCreateOrder() {
			const oRouter = this.getOwnerComponent().getRouter();
			oRouter.navTo("RouteOverview");
		},

		doCreateOrder() {
			var date = new Date();
			var that = this;
			var oProductInput = this.getView().byId("productInput");
			var oCustomerInput = this.getView().byId("customerInput");
			var oIssueContentTextArea = this.getView().byId("issueContentTextArea");
			var oRepairContentTextArea = this.getView().byId("repairContentTextArea");
			if (oProductInput.getValue() == "") {
				sap.m.MessageToast.show("请选择ProductID");
				return
			}
			if (oCustomerInput.getValue() == "") {
				sap.m.MessageToast.show("请选择CustomerID");
				return
			}
			if (oIssueContentTextArea.getValue() == "") {
				sap.m.MessageToast.show("请填写Issue Content");
				return
			}
			if (oRepairContentTextArea.getValue() == "") {
				sap.m.MessageToast.show("请填写Repair Content");
				return
			}

			var oModel = new sap.ui.model.odata.v2.ODataModel("/sap/opu/odata/sap/ZGBLMTORDER_TRN_SRV/", {
				serviceUrl: "/sap",
				useBatch: false
			});
			var oEntry = {};
			oEntry.productID = oProductInput.getValue();
			oEntry.customerNo = oCustomerInput.getValue();
			oEntry.issContent = oIssueContentTextArea.getValue();
			oEntry.repContent = oRepairContentTextArea.getValue();
			oEntry.issDate = date;

			oModel.create("/ENTITY001Set", oEntry, {
				success: function (data) {
					sap.m.MessageToast.show("创建成功");
					const oRouter = that.getOwnerComponent().getRouter();
					oRouter.navTo("RouteOverview");
				},
				error: function (error) {
					sap.m.MessageToast.show(error.message);
				}
			});
		}
	});
});